package com.ba.base.view.web

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import com.screx.mcloud.lib.view.AbsThemeActivity
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView

class H5WebChromeClient(
    private val mActivity: AppCompatActivity,
    private val mWebView: H5VideoWebView
) : WebChromeClient() {

    companion object {
        const val LEFT = 0
        const val CENTER = 1
        const val DEFAULT_MARGIN = 20

        var requestCode = 2020
    }

    private val mFullScreenViewParams = FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT
    )

    private var mHandler: Handler? = null
    private var mHideRun: Runnable? = null

    var mCustomView: View? = null

    private var mCustomViewCallBack: IX5WebChromeClient.CustomViewCallback? = null
    private var mFullContainerView: FrameLayout? = null
    private var mHeight = 0
    private var mResourceId = -1
    private var mBackMargin = DEFAULT_MARGIN

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onShowCustomView(
        view: View,
        callback: IX5WebChromeClient.CustomViewCallback
    ) {
        showCustomView(view, callback)
        //展示全屏设置为横屏
        mActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

        // 全屏展示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
            mActivity.window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )
        } else {
            // 全屏显示，隐藏状态栏
            mActivity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
        }
    }

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onHideCustomView() {
        hideCustomView()
        //隐藏全屏设置为竖屏
        mActivity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        mActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

    override fun onShowFileChooser(
        webView: WebView?,
        filePathCallback: ValueCallback<Array<Uri>>,
        fileChooserParams: FileChooserParams?
    ): Boolean {
        openFileChooserImplForAndroid5(filePathCallback)
        return true
    }

    private var webFileCallback: ValueCallback<Array<Uri>>? = null

    private fun openFileChooserImplForAndroid5(uploadMsg: ValueCallback<Array<Uri>>) {
        webFileCallback = uploadMsg
        val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
        contentSelectionIntent.type = "*/*"
        val chooserIntent = Intent(Intent.ACTION_CHOOSER)
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "文件选择")

        if (mActivity is AbsThemeActivity) {
            mActivity.mH5WebChromeClient = this
        }
        mActivity.startActivityForResult(
            chooserIntent, requestCode
        )
    }

    fun webFileCallback(mUri: Uri?) {
        if (mUri != null) {
            webFileCallback?.onReceiveValue(arrayOf(mUri))
        } else {
            webFileCallback?.onReceiveValue(arrayOf())
        }
        webFileCallback = null
    }

    /**
     * 展示自定义全屏窗口
     *
     * @param view     全屏View
     * @param callback [WebChromeClient.CustomViewCallback]
     */
    private fun showCustomView(
        view: View,
        callback: IX5WebChromeClient.CustomViewCallback?
    ) {
        if (mCustomView != null) {
            callback?.onCustomViewHidden()
            return
        }
        val decorView = mActivity.window.decorView as FrameLayout
        mFullContainerView = object : FrameLayout(mActivity) {
        }
        mFullContainerView?.setBackgroundColor(Color.BLACK)
        mFullContainerView?.addView(view, mFullScreenViewParams)
        decorView.addView(mFullContainerView, mFullScreenViewParams)
        mCustomView = view
        setStatusBarVisibility(false)
        mCustomViewCallBack = callback
        mWebView.visibility = View.INVISIBLE
    }

    /**
     * 隐藏自定义全屏窗口
     */
    fun hideCustomView() {
        if (mCustomView == null) {
            return
        }
        setStatusBarVisibility(true)
        val decorView = mActivity.window.decorView as FrameLayout
        decorView.removeView(mFullContainerView)
        mFullContainerView = null
        mCustomView = null
        mCustomViewCallBack?.onCustomViewHidden()
        mHideRun?.let {
            mHandler?.removeCallbacks(it)
        }
        mHandler = null
        mWebView.visibility = View.VISIBLE
    }

    /**
     * 设置状态栏是否可见
     *
     * @param visible 状态栏是否可见
     */
    private fun setStatusBarVisibility(visible: Boolean) {
        val flag = if (visible) 0 else WindowManager.LayoutParams.FLAG_FULLSCREEN
        mActivity.window.setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    /**
     * 设置Back图片
     *
     * @param resourceId 资源Id
     */
    fun setBackResource(@DrawableRes resourceId: Int) {
        mResourceId = resourceId
    }

    /**
     * 设置返回按钮左间距
     *
     * @param backMargin 间距具体值
     */
    fun setBackLeftMargin(backMargin: Int) {
        mBackMargin = backMargin
    }

    /**
     * @param height TitleView高度
     */
    fun setHeight(height: Int) {
        setHeight(height, false)
    }

    /**
     * 设置TitleView高度
     *
     * @param height TitleView高度
     * @param isDp   但是是否是dp
     */
    fun setHeight(height: Int, isDp: Boolean) {
        mHeight = if (isDp) {
            dip2px(height.toFloat())
        } else {
            height
        }
    }

    /**
     * dip转px
     *
     * @param dipValue 需要转换的dp
     * @return px 转换后的px
     */
    private fun dip2px(dipValue: Float): Int {
        val dm = mActivity.applicationContext.resources.displayMetrics
        val density = dm.density
        return (dipValue * density + 0.5f).toInt()
    }

}